<template>
  <a-select
    show-search
    :not-found-content="state.agentSelectionFetching ? undefined : null"
    placeholder="输入手机号进行搜索"
    :filter-option="false"
    @search="value => getAgentList(agentListCurrentPhone = value, agentListCurrentPage = 1)"
    @change="handleAgentSelected"
    @popupScroll="fetchMoreAgent"
  >
    <a-select-option v-for="agent in agents" :key="agent.id">
      {{ agent.name }} {{ agent.phone }}
    </a-select-option>

    <a-spin v-if="state.agentSelectionFetching" slot="notFoundContent" size="small"/>
  </a-select>
</template>

<script>
import { getAgentList } from '@/api/agent'

export default {
  name: 'AgentByPhoneSelection',
  props: {},
  watch: {},
  created () {

  },
  data () {
    return {
      state: {
        agentSelectionFetching: false,
        isFinished: false
      },

      agents: [],
      agentIdWithItem: [],
      currentSelectAgentObj: {}
    }
  },
  methods: {
    getAgentList (phone, page) {
      if (phone === '' || this.state.agentSelectionFetching) {
        return
      }

      this.state.agentSelectionFetching = true
      if (page === 1) {
        this.agents = []
        this.agentIdWithItem = {}
        this.state.isFinished = false
      }

      getAgentList({
        phone,
        page,
        select: ['id', 'name', 'phone', 'team_performance'],
        with_labels: 0
      }).then(res => {
        if (res.data) {
          if (res.current_page >= res.last_page) {
            this.state.isFinished = true
          }
          res.data.forEach(item => {
            this.agents.push(item)
            this.agentIdWithItem[item.id] = item
          })
        }
      }).finally(_ => {
        this.state.agentSelectionFetching = false
      })
    },
    /**
     * 加载更多
     * @param e
     */
    fetchMoreAgent (e) {
      const { target } = e
      const rmHeight = target.scrollHeight - target.scrollTop
      const clHeight = target.clientHeight
      if (rmHeight < clHeight + 30 && !this.state.isFinished && !this.state.agentSelectionFetching) {
        this.getAgentList(this.agentListCurrentPhone, ++this.agentListCurrentPage)
      }
    },
    handleAgentSelected (value) {
      this.currentSelectAgentObj = this.agentIdWithItem[value]

      this.$emit('input', this.currentSelectAgentObj)
      this.$emit('change', this.currentSelectAgentObj)
    }
  }
}
</script>

<style scoped>

</style>
